//
//  BidViewController.swift
//  cxd4iphone
//
//  Created by hexy on 12/2/15.
//  Copyright © 2015 hexy. All rights reserved.
//

import UIKit
import MJRefresh

private struct kConstraints {
    
    static let headerRect: CGRect = CGRectMake(0, 0, xx_screenWidth(), xx_screenHeight()-64-xx_height(190))
    static let footerRect: CGRect = CGRectMake(0, 0, xx_screenWidth(), xx_height(190))
}

class BuyViewController: BaseTableViewController {
    
    private lazy var buyListViewModel = BuyListViewModel()
    
    var bidID = String()
    
    init(bidID: String) {

        super.init(style: .Plain)
        
        self.title = "购买"
        self.bidID = bidID
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tap"))
        
        startObserverNotification()
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
            
            self.loadData()
        })
        tableView.mj_header.beginRefreshing()
//        loadData()
        
    }
    func tap() {
        self.view.endEditing(true)
    }
    private func startObserverNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "move:", name:UIKeyboardWillShowNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reset:", name:UIKeyboardWillHideNotification, object: nil)
    }
    
    @objc private func move(note: NSNotification) {
        
        
        
        let height = (note.userInfo![UIKeyboardFrameBeginUserInfoKey]?.CGRectValue.size.height)!
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        let curve = note.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        
        UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.transform = CGAffineTransformMakeTranslation(0, -height)
        }
    }
    
    @objc private func reset(note: NSNotification) {
        
        
        
//        let height = (note.userInfo![UIKeyboardFrameBeginUserInfoKey]?.CGRectValue.size.height)!
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        let curve = note.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        
        UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.transform = CGAffineTransformIdentity
        }
    }

    private func loadData() {
        
//        guard let id = bidID else { return }
//        xx_showHUD(nil)
        buyListViewModel.loadBidDetail(bidID).subscribeError({ (error) -> Void in
            
                xx_showError(error)
            
            }) { () -> Void in
                
//                xx_hideHUD()
                self.tableView.mj_header.endRefreshing()
                self.header.bidViewModel = self.buyListViewModel.bidViewModel
                self.footer.bidViewModel = self.buyListViewModel.bidViewModel
                xx_print(self.buyListViewModel.bidViewModel?.bidModel)
        }
    }
    override func makeTableView() {
        
        self.tableListViewModel = buyListViewModel
        
        tableView.tableHeaderView = header
        
        header.pDetaiBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) -> Void in
            
            self.pushToBidDetail()
        }
        header.pRiskBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) -> Void in
            
            self.pushToBidRisk()
        }
        header.bidHistoryBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) -> Void in
            
           self.pushToBidInvestRecord()
        }

        tableView.tableFooterView = footer
        footer.depositBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) -> Void in
            
            self.navigationController?.pushViewController(DepositViewController(aTitle: "充值"), animated: true)
        }
        
        footer.bidTextField.rac_textSignal().subscribeNext({ (text) -> Void in
            
            let len = (text as! String).lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
            guard let vm = self.buyListViewModel.bidViewModel else { return }
            let value = (text as! NSString).doubleValue
            
            
            let str = ("\(value / 100)" as NSString)
            
            let v = str.substringFromIndex(str.rangeOfString(".").location)
            
            self.footer.bidTextField.layer.borderColor = (v == ".0") ? Define.textFieldColor : Define.redColor.CGColor
            
            if len > 2 {
                
                vm.inputValue = value
                 self.footer.expectProfitNumLabel.text = vm.expectProfit
                
            } else {
                
                self.footer.bidTextField.layer.borderColor = Define.textFieldColor
                self.footer.expectProfitNumLabel.text = "0.00"

            }
            
          
        })

        footer.investBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) -> Void in
            
            self.view.endEditing(true)
            if let money = self.footer.bidTextField.text {
                
                xx_print(money)
                xx_print(self.bidID)
                
                YPRequestViewModel.shared.invest(self.bidID, investMoney: money).subscribeError({ (error) -> Void in
                    
                        xx_showError(error)
                    
                    }, completed: { () -> Void in
                        
                        let vc = WebViewController(title: "投标", htmlStr: YPRequestViewModel.shared.html)
                        
                        self.navigationController?.pushViewController(vc, animated: true)

                })
            }
        }
    }
    
    private lazy var header = BidInfoTopView(frame: kConstraints.headerRect)
    private lazy var footer = BidInfobottomView(frame: kConstraints.footerRect)

    
    func pushToBidDetail() {
        
        let vc = BidDetailViewController(bidViewModel: buyListViewModel.bidViewModel!)
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToBidRisk() {
        
        let vc = BidRiskViewController(bidViewModel: buyListViewModel.bidViewModel!)
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToBidInvestRecord() {
        
        let bidId = (buyListViewModel.bidViewModel?.bidModel.id)!
        let vc = BidInvestRecordViewController(bidID: bidId)
        self.navigationController?.pushViewController(vc, animated: true)
        
    }

}
